<!-- src/views/forum/index.vue -->
<template>
  <div class="forum-container">
    <div class="forum-header">
      <h2>论坛社区</h2>
      <el-button type="primary" @click="goToCreatePost">发布新帖</el-button>
    </div>

    <!-- 帖子列表 -->
    <el-table
      :data="postList"
      style="width: 100%"
      v-loading="loading"
      @row-click="viewPostDetail"
      row-key="id"
      class="post-table"
    >
      <el-table-column prop="title" label="标题" min-width="200">
        <template slot-scope="scope">
          <div class="post-title">{{ scope.row.title }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="content" label="内容预览" min-width="300">
        <template slot-scope="scope">
          <div class="post-content-preview">
            {{ scope.row.content | truncate }}
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="userName"
        label="发帖人"
        width="120"
      ></el-table-column>
      <el-table-column prop="createTime" label="发布时间" width="180">
        <template slot-scope="scope">
          {{ formatDate(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120" fixed="right">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            @click.stop="viewPostDetail(scope.row)"
          >
            查看详情
          </el-button>
          <el-button
            v-if="canDelete(scope.row.userId)"
            type="text"
            size="small"
            @click.stop="handleDeletePost(scope.row)"
            class="delete-btn"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageIndex"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import forumApi from "@/api/forum";
import { mapState } from "vuex";

export default {
  name: "ForumList",
  data() {
    return {
      postList: [],
      loading: false,
      pageIndex: 1,
      pageSize: 10,
      total: 0,
    };
  },
  computed: {
    ...mapState("user", ["userInfo"]),
  },
  filters: {
    truncate(text) {
      if (!text) return "";
      return text.length > 100 ? text.substring(0, 100) + "..." : text;
    },
  },
  created() {
    this.checkUserProfile();
    this.fetchPostList();
  },
  methods: {
    checkUserProfile() {
      if (!this.userInfo || !this.userInfo.id) {
        this.$message.error("请先登录");
        this.$router.push("/login");
        return false;
      }
      return true;
    },
    // 获取帖子列表
    fetchPostList() {
      if (!this.checkUserProfile()) return;

      this.loading = true;
      forumApi
        .getPostPage({
          pageIndex: this.pageIndex,
          pageSize: this.pageSize,
        })
        .then((res) => {
          if (res.code === 1) {
            this.postList = res.response.list || [];
            this.total = res.response.total || 0;
          } else {
            this.$message.error(res.message || "获取帖子列表失败");
          }
        })
        .catch((error) => {
          console.error("获取帖子列表失败:", error);
          this.$message.error("获取帖子列表失败");
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return "";
      const date = new Date(dateString);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(
        2,
        "0"
      )}-${String(date.getDate()).padStart(2, "0")} ${String(
        date.getHours()
      ).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`;
    },
    // 检查是否有删除权限
    canDelete(postUserId) {
      // 管理员(role=3)或自己发的帖子可以删除
      return (
        this.userInfo &&
        (this.userInfo.id === postUserId || this.userInfo.role === 3)
      );
    },
    // 查看帖子详情
    viewPostDetail(row) {
      this.$router.push({
        path: "/forum/detail",
        query: { id: row.id },
      });
    },
    // 跳转到发帖页面
    goToCreatePost() {
      this.$router.push("/forum/create");
    },
    // 删除帖子
    handleDeletePost(post) {
      this.$confirm("确定要删除这个帖子吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          forumApi
            .deletePost(post.id, this.userInfo.id, this.userInfo.role)
            .then((res) => {
              if (res.code === 1) {
                this.$message.success("删除成功");
                this.fetchPostList();
              } else {
                this.$message.error(res.message || "删除失败");
              }
            })
            .catch((error) => {
              console.error("删除帖子失败:", error);
              this.$message.error("删除失败");
            });
        })
        .catch(() => {
          // 取消删除操作
        });
    },
    // 页码变化
    handleCurrentChange (val) {
      this.pageIndex = val
      this.fetchPostList()
    },
    // 每页条数变化
    handleSizeChange (val) {
      this.pageSize = val
      this.pageIndex = 1
      this.fetchPostList()
    },
  },
};
</script>

<style scoped>
.forum-container {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
}

.forum-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.post-table {
  margin-bottom: 20px;
  cursor: pointer;
}

.post-title {
  font-weight: bold;
  color: #303133;
}

.post-content-preview {
  color: #606266;
  white-space: normal;
  word-break: break-all;
  line-height: 1.5;
}

.pagination-container {
  text-align: center;
  margin-top: 20px;
}

.delete-btn {
  color: #f56c6c;
  margin-left: 10px;
}

.el-table__row:hover {
  background-color: #f5f7fa;
}
</style>
